<template>
  <div class="role">
    <PageSearch
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="handleResetClick"
      @queryBtnClick="handleQueryClick"
    />
    <div class="content">
      <PageContent
        ref="pageContentRef"
        :contentTableConfig="contentTableConfig"
        pageName="role"
        @new-btn-click="handleNewData"
        @edit-btn-click="handleEditData"
        @look-btn-click="handleLookData"
      />
      <PageModal
        :modalConfig="modalConfig"
        ref="pageModalRef"
        :defaultInfo="defaultInfo"
        pageName="role"
        :otherInfo="otherInfo"
      >
        <div class="el-tree">
          <el-tree
            ref="elTreeRef"
            :data="menus"
            show-checkbox
            node-key="id"
            :props="{ children: 'children', label: 'name' }"
            @check="handleCheckChange"
          />
        </div>
      </PageModal>
    </div>
  </div>
</template>

<script setup lang="ts">
import PageSearch from '@/components/page-search/index'
import PageContent from '@/components/page-content/index'
import PageModal from '@/components/page-modal'
import { searchFormConfig } from './config/pageSearch.config'
import { contentTableConfig } from './config/pageContent.config'
import { modalConfig } from './config/pageModal.config'
import { usePageSearch } from '@/hooks/usePageSearch'
import { useModal } from '@/hooks/useModal'
import { useStore } from '@/store'
import { computed, nextTick, ref } from 'vue'
import { menuMapLeafKeys } from '@/utils/map-menus'
import { ElTree } from 'element-plus'

const store = useStore()
const menus = computed(() => store.state.menuList)

const otherInfo = ref({})
// 	点击节点复选框之后触发的回调函数
const handleCheckChange = (data1: any, data2: any) => {
  const checkedKeys = data2.checkedKeys
  const halfCheckedKeys = data2.halfCheckedKeys
  const menuList = [...checkedKeys, ...halfCheckedKeys]
  otherInfo.value = { menuList }
}

// elTreeRef 获取el-tree组件
const elTreeRef = ref<InstanceType<typeof ElTree>>()
/**
 * editCallback 点击编辑按钮的回调,控制el-tree数据回显
 * leftKeys [39, 40]
 * setCheckedKeys 设置目前选中的节点，使用此方法必须设置 node-key 属性
 */
const editCallback = (item: any) => {
  const leftKeys = menuMapLeafKeys(item.menuList)
  nextTick(() => {
    elTreeRef.value?.setCheckedKeys(leftKeys, false)
  })
}

// 调用hooks公共的方法
const [handleResetClick, handleQueryClick, pageContentRef] = usePageSearch()

const [
  handleNewData,
  handleEditData,
  handleLookData,
  defaultInfo,
  pageModalRef
] = useModal(modalConfig, undefined, editCallback)
</script>

<style scoped lang="less">
.content {
  margin-top: 20px;
  padding: 20px;
  background-color: #ffffff;
  .el-tree {
    margin-left: 10px;
  }
}
</style>
